<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户账号" prop="account">
        <el-input v-model="queryParams.account" placeholder="请输入用户账号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入手机号码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="用户分组" prop="groupId">
        <el-select v-model="queryParams.groupId" placeholder="请选择用户分组">
          <el-option
            v-for="item in groupOptions"
            :key="item.id"
            :label="item.groupName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['user:s:create']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['user:s:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-present" size="mini" @click="openGrantCouponDialog">
          发放优惠券
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete"
                   v-hasPermi="['user:s:delete']">批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <!--        <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete"-->
        <!--                   v-hasPermi="['user:s:delete']">批量删除</el-button>-->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!--            <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">-->
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange">
      <!--              //单选框获取id-->
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户id" align="center" prop="uid" />
      <el-table-column label="用户账号" align="center" prop="account" />
      <el-table-column label="用户分组" align="center" prop="groupName" />
      <el-table-column label="等级标签" align="center" prop="tagName" />
      <el-table-column label="用户昵称" align="center" prop="nickname" />
      <!--      <el-table-column label="用户头像" align="center" prop="avatar" />-->
      <el-table-column label="用户头像" align="center" width="80">
        <template #default="{row}">
          <el-image
            v-if="row.avatar"
            style="width: 70px; height: 70px; cursor: pointer"
            :src="row.avatar"
            :preview-src-list="[row.avatar]"
            hide-on-click-modal
          ></el-image>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center" prop="phone" />
      <el-table-column label="用户余额" align="center" prop="nowMoney" />
      <el-table-column label="用户剩余积分" align="center" prop="integral" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.uid)"
                     v-hasPermi="['user:s:update']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['user:s:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <sForm ref="formRef" @success="getList" />

    <el-dialog title="发放优惠券" :visible.sync="grantCouponDialogVisible" width="800px">
      <el-table :data="couponList" v-loading="couponLoading" style="width: 100%">
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="优惠券名称" prop="name" />
        <el-table-column label="优惠劵面值" prop="money" />
        <el-table-column label="最低消费额" prop="minPrice" />
        <el-table-column label="有效期限" width="320">
          <template v-slot="scope">
            <span v-if="scope.row.useStartTime && scope.row.useEndTime">
              {{ parseTime(scope.row.useStartTime) }} - {{ parseTime(scope.row.useEndTime) }}
            </span>
            <span v-else>不限时</span>
          </template>
        </el-table-column>
        <el-table-column label="剩余数量" prop="lastTotal" />
        <el-table-column label="操作" width="120">
          <template v-slot="scope">
            <el-button size="mini" type="primary" @click="grantCoupon(scope.row)">发放</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import * as sApi from '@/api/user/users';
import sForm from './sForm.vue';
import * as groupApi from "@/api/user/usergroup";
import * as StoreCouponApi from '@/api/discount/storecoupon';
import * as StoreCouponUserApi from '@/api/discount/storecouponuser';
export default {
  name: "s",
  components: {
    sForm,
  },
  data() {
    return {
      groupOptions: [],
      selectedRows: [], // 存储选中的行
      selectedIds: [], // 存储选中的ID
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        account: null,
        phone: null,
        groupId: null,
      },
      grantCouponDialogVisible: false,
      couponList: [],
      couponLoading: false,
    };
  },
  created() {
    this.getGroupOptions();
    this.getList();
  },
  methods: {
    async getGroupOptions() {
      try {
        const res = await groupApi.getGroupPage({
          pageNo: 1,
          pageSize: 100  // 使用允许的最大值
        });
        console.log('用户分组数据:', res.data.list);
        this.groupOptions = res.data.list || [];
      } catch (error) {
        console.error('获取用户分组失败:', error);
        this.$modal.msgError('获取用户分组失败');
      }
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.selectedIds = selection.map(item => item.uid);
    },

    // 修改删除方法
    async handleDelete(row) {
      let ids = [];
      if (row.uid) {
        // 单个删除
        ids = [row.uid];
      } else {
        // 批量删除
        if (this.selectedIds.length === 0) {
          this.$modal.msgWarning("请先选择要删除的用户");
          return;
        }
        ids = this.selectedIds;
      }

      await this.$modal.confirm(`是否确认删除用户编号为"${ids.join(',')}"的数据项?`);
      try {
        // 修改为调用批量删除接口
        await sApi.deletesBatch(ids);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
        this.selectedRows = [];
        this.selectedIds = [];
      } catch {}
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await sApi.getsPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    // async handleDelete(row) {
    //   const uid = row.uid;
    //   await this.$modal.confirm('是否确认删除用户编号为"' + uid + '"的数据项?')
    //   try {
    //    await sApi.deletes(uid);
    //    await this.getList();
    //    this.$modal.msgSuccess("删除成功");
    //   } catch {}
    // },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有用户数据项?');
      try {
        this.exportLoading = true;
        const data = await sApi.exportsExcel(this.queryParams);
        this.$download.excel(data, '用户.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    async openGrantCouponDialog() {
      this.grantCouponDialogVisible = true;
      this.couponLoading = true;
      try {
        const res = await StoreCouponApi.getStoreCouponPage({ pageNo: 1, pageSize: 100 });
        // 过滤出还在有效期内的优惠券
        this.couponList = (res.data.list || []).filter(coupon => this.isCouponValid(coupon));
      } finally {
        this.couponLoading = false;
      }
    },
    async grantCoupon(row) {
      if (!this.selectedIds || this.selectedIds.length === 0) {
        this.$message.warning('请先在用户列表选择要发放的用户');
        return;
      }
      // 二次确认
      await this.$confirm(
        `确定要给选中的${this.selectedIds.length}个用户发放优惠券【${row.name}】吗？`,
        '提示',
        { type: 'warning' }
      );
      try {
        for (const uid of this.selectedIds) {
          await StoreCouponUserApi.createStoreCouponUserDirectForSingleUser({
            uid,
            couponId: row.id
          });
        }
        this.$message.success('发放成功');
        this.grantCouponDialogVisible = false;
      } catch (e) {
        this.$message.error('发放失败');
      }
    },
    // 检查优惠券是否在有效期内
    isCouponValid(coupon) {
      const now = new Date();
      // 只要没过期就显示（有useEndTime且已过期才不显示）
      if (coupon.useEndTime) {
        const endTime = new Date(coupon.useEndTime);
        if (now > endTime) {
          return false; // 已过期
        }
      }
      return true; // 其他情况都显示
    },
    // 时间格式化方法（如已有可复用）
    parseTime(time) {
      if (!time) return '';
      const date = new Date(time);
      return date.getFullYear() + '-' +
        String(date.getMonth() + 1).padStart(2, '0') + '-' +
        String(date.getDate()).padStart(2, '0') + ' ' +
        String(date.getHours()).padStart(2, '0') + ':' +
        String(date.getMinutes()).padStart(2, '0') + ':' +
        String(date.getSeconds()).padStart(2, '0');
    },
  }
};
</script>
